const RIDER = uniCloud.importObject("rider")
const ORDERS = uniCloud.importObject("order", {customUI: true})
/**
 * - 更换骑手
 * @param orderNo 需要操作的订单单号
 * @param riderData 更换新骑手的信息
 * @param money 	此单配送费
 * @param currentRiderId 当前骑手ID
*/
export async function updateRider(orderNo,riderData ,money,currentRiderId){
	if (!orderNo || !riderData || money < 0) {
		return { code:500,error:'参数不全',orderNo,riderData,money,currentRiderId }
	}
	const db = uniCloud.database()
	try{
		let Data = {
			avatar:riderData.avatar,
			mobile:riderData.mobile,
			nickname:riderData.text,
			user_id:riderData._id,
			connect_time:Date.now()
		}
		if (!!currentRiderId) {
			const currentRider = await RIDER.setRiderEarningsAndOrderNumbers(currentRiderId,-money,-1)
		}
		const tempNewRider = await RIDER.setRiderEarningsAndOrderNumbers(riderData._id,money,1)
		const result = await db.collection("orders").where({order_no:orderNo}).update({rider:Data})
		let http = 'https://api.yipaidaojia.com/index.php/api/aliyun_voice'
		let data = { tel: riderData.mobile, token: '86f24d4bf67694706a347dc36f3365c0'}
		uni.request({method: 'POST',url: http,data: data})
		return {
			code:200,
			result:result.result
		}
	}catch(error){
		return{
			code:404,
			error
		}
	}
}

/**
 * - 修改订单状态
 * @param orderNo 需要操作的订单单号
 * @param status 需要操作的订单单号
*/
export async function updateStatus(orderNo,status,payDate,createDate){
	if (!orderNo || !status) {
		return { code:500,error:'参数不全',orderNo,status}
	}
	const db = uniCloud.database()
	let updateData ;
	try{
		if (!payDate) {
			updateData = {
				status,
				pay_date:createDate
			}
		}else {
			updateData = {
				status
			}
		}
		const orderStatus = {
			value:status.value ,
			text: status.text,
			create_time: Date.now()
		}
		ORDERS.updateOrderStatusToCancel(orderNo, orderStatus)
		let result = await db.collection("orders").where({order_no:orderNo}).update(updateData)
		return {
			code:200,
			result:result.result
		}
	}catch(error){
		return{
			code:404,
			error
		}
	}
}